<template> <!-- PK准备页面 -->
	<view class="wrap" v-if="!isLoading">
		<view class="layout-position">
			<!-- 背景音乐 -->
			<view class="layout-music flex justify-end">
				<view class="text m-right-30">背景音乐</view>
				<u-switch v-model="switchValue" size="32" @change="musicDo"></u-switch>
				<!-- activeColor="#4395f9" -->
			</view>
			<!-- 多方好友 -->
			<view class="layout-multiple flex justify-start flex-wrap">
				<view class="item third flex direction-column justify-center align-center"
					v-for="(item,index) in userList">

					<avatar-image :url="item.avatar_url" :width="120" />
					<view class="nickname text-single m-top-10" v-if="item.user_id>0">{{item.nick_name}}</view>
					<view class="nickname text-single m-top-10" v-else>空闲</view>
				</view>

			</view>
			<!-- 邀请、加入、等待 -->
			<view class="layout-wait">
				<view class="m-top-20">

					<!-- 加入按钮 -->
					<u-button v-if="isRole == 1&&userInfo.user_id!=roomInfo.user_id" :custom-style="resultBtn"
						shape="circle" @click="handJoin()">加入房间</u-button>
					<!-- 开始按钮 -->
					<u-button v-if="isRole == 2&&userInfo.user_id==roomInfo.user_id" :custom-style="resultBtn"
						shape="circle" @click="handRoom">开始对战</u-button>


					<!-- 邀请按钮 -->

					<button class="share-btn" open-type="share" v-if="isRole == 0||isRole == 1" style="margin: 10rpx;">
						邀请好友
					</button>

					<!-- 加入按钮 -->
					<u-button v-if="isRole == 2&&userInfo.user_id!=roomInfo.user_id" :custom-style="resultBtn"
						shape="circle" @click="logout">退出房间</u-button>
				</view>
				<view class="ready m-top-10" v-if="isRole == 2&&userInfo.user_id!=roomInfo.user_id">已准备，等待房主开始</view>
			</view>
		</view>
		<!-- 右下角背景图 -->
		<view class="hi">
			<image class="full" src="/static/image/hi.png" mode=""></image>
		</view>
	</view>
</template>

<script>
	import AvatarImage from '@/components/avatar-image'
	import {
		getSocket
	} from '@/utils/uni-socket'
	import * as GameRoomApi from '@/api/dati/rooms'
	import * as UserApi from '@/api/user'



	export default {
		components: {

			AvatarImage
		},
		data() {
			return {
				socketTask: null,
				isLoading: true,
				userList: [{
					user_id: 0,
					avatar_url: ''
				}, {
					user_id: 0,
					avatar_url: ''
				}, {
					user_id: 0,
					avatar_url: ''
				}, {
					user_id: 0,
					avatar_url: ''
				}, {
					user_id: 0,
					avatar_url: ''
				}, {
					user_id: 0,
					avatar_url: ''
				}],
				resultBtn: {
					color: '#ffffff',
					background: '#0197F8',
				},
				src: 'https://cdn.uviewui.com/uview/album/1.jpg',
				switchValue: true,
				isPopup: false,
				isRole: 0, // 邀请-0、加入-1、开始-2、进行中-3
				is_play: true,
				audio: null,
				audio_url: '',
				roomId: 0,
				roomInfo: {},
				userInfo: {},
				count: 1
			};
		},

		async onLoad(options) {
			// if (options.isRole == 0) {
			// 	this.addRoom()
			// } else {
			// 	console.log('邀请函打开')
			// 	this.handInit(options.roomId)
			// }
			// this.isRole = options.isRole
			// this.roomId = options.roomId
			// if (options.roomId) {
			// 	this.getRoom(options.roomId)
			// } else {
			// 	console.log(787)
			// 	this.getRoom(0)
			// }
			this.getUserInfo()
			this.roomId = options.roomId ? options.roomId : 0
			this.socketTask = uni.connectSocket({
				url: 'wss://xiaolanghua.zhanyuankj.cn/wss?roomId=' + this.roomId, // 替换为你的WebSocket服务器地址
				success: () => {
					console.log('连接成功');



				},
				fail: (err) => {
					console.error('连接失败', err);
				}
			});

			this.socketTask.onOpen(() => {


				//this.handInit(this.roomId)
				if (this.roomId > 0) {
					this.getRoom(this.roomId)
				} else {
					this.addRoom()
				}

			});
			// 监听服务器消息
			this.socketTask.onMessage((res) => {
				console.log(89)
				console.log(res)
				const data = JSON.parse(res.data);
				// 根据消息类型处理
				switch (data.type) {
					case 'join_room_success':
						// 加入房间成功
						break;
					case 'new_question':
						// 收到新题目
						this.setData({
							question: data.question,
							options: data.options
						});
						break;
					case 'answer_result':
						// 答题结果，包括是否正确、正确答案、得分等
						break;
					case 'room_rank':
						// 房间内实时排名
						this.setData({
							rankList: data.rankList
						});
						break;
						// 其他消息类型...
				}
			});




		},
		onUnload() {
			if (this.audio) {
				this.audio.stop();
			}
			console.log(45)
			clearInterval(this.timer);
		},
		methods: {
			createRoom() {
				this.socketTask.send({
					data: JSON.stringify({
						type: 'create_room',
						room_id: 0,
						user_id: 1, // 假设有用户信息
						nickname: 1
					}),
					success: () => {
						console.log('加入房间请求发送成功');
					}
				});
			},
			endGame(data) {
				this.socketTask.close();
				uni.showModal({
					title: '游戏结束',
					content: `获胜者: ${data.winner} 得分: ${data.score}`
				});
			},
			joinRoom(roomId) {
				this.socketTask.send({
					data: JSON.stringify({
						type: 'join_room',
						room_id: roomId,
						user_id: this.userInfo.id, // 假设有用户信息
						nickname: this.userInfo.nickname
					}),
					success: () => {
						console.log('加入房间请求发送成功');
					}
				});
			},
			submitAnswer(answer) {
				this.socketTask.send({
					data: JSON.stringify({
						type: 'submit_answer',
						roomId: this.roomId,
						userId: this.userId,
						questionId: this.currentQuestion.id,
						answer: answer // 选择的答案选项
					}),
					success: () => console.log('答案已提交')
				});
			},

			musicDo(e) {
				console.log(e)
				if (e == false) {
					this.audio.stop();
				} else {
					if (!this.audio) {
						var audio_url = this.audio_url
						this.skvido(audio_url)
					} else {
						this.audio.play();
					}

				}
			},

			getUserInfo() {
				UserApi.info()
					.then(result => {
						this.userInfo = result.data.userInfo
						this.audio_url = result.data.userInfo.audio_url

						if (result.data.userInfo.is_music) {
							this.skvido(result.data.userInfo.audio_url)
							this.switchValue = true

						} else {
							this.switchValue = false
						}
						this.isLoading = false


					})
			},
			skvido(audio_url) {

				console.log(556)
				// 创建音频对象
				this.audio = uni.createInnerAudioContext();



				// 设置音频源
				//this.audio.src = 'https://safe.gxgyl.com/uploads/bg.mp3';
				this.audio.src = audio_url;



				// 播放音频
				this.audio.play();
				this.is_play = true

				// 监听音频播放完成事件
				this.audio.onEnded(() => {
					//this.is_play = false
					this.skvido(audio_url)
					console.log('音频播放完成');
				});

				// 监听音频播放错误事件
				this.audio.onError((err) => {
					console.log('音频播放错误', err);
				});
				return
				let _this = this;
				plugin.textToSpeech({
					lang: "zh_CN",
					tts: true,
					content: _this.timu_title,
					success: function(res) {
						console.log("succ tts", res.filename)

						let music = null;
						music = uni.createInnerAudioContext(); //创建播放器对象
						music.src = res.filename;
						music.play(); //执行播放
						music.onEnded(() => {

							//播放结束
							//_this.is_play = false
							//music = null;
						});
					},
					fail: function(res) {
						// console.log("fail tts", res)
					}
				})
			},

			getRoom(roomId) {
				GameRoomApi.detail({
						roomId: roomId
					})
					.then(result => {
						console.log(99)
						//console.log(result.data.detail)
						this.roomInfo = result.data.room
						var list = result.data.userList
						var userList=this.userList
						userList.forEach((item, index) => {
							if (list[index]) {
								item.nick_name = list[index].nick_name
								item.avatar_url = list[index].avatar_url
								item.user_id = list[index].user_id
								console.log(list[index])
							}
							return item
						})
						console.log(userList)
						
						this.userList=userList

						//this.isRole = result.data.detail.isRole


					})
			},
			addRoom() {

				GameRoomApi.add()
					.then(result => {
						this.roomId = result.data.room_id
						this.userList[0].user_id = this.userInfo.user_id
						this.userList[0].avatar_url = this.userInfo.avatar_url
						this.userList[0].nick_name = this.userInfo.nick_name
						this.isLoading = false
						//this.handInit0(this.roomId)


					})
			},
			logout() {
				GameRoomApi.logout({
						roomId: this.roomId
					})
					.then(result => {
						this.isRole = 1
						uni.reLaunch({
							url: '/pages/index/index'
						})

					})
			},
			//邀请后的倒计时
			handInit0(roomId) {
				const that = this

				// 开始倒计时
				this.countdown = 120;
				this.timer = setInterval(() => {
					this.countdown--;
					console.log(this.countdown)

					GameRoomApi.getUserList({
						roomId: roomId,
						userId: 0
					}).then(result => {
						var users = result.data.count


						if (users >= 2) {

							console.log('成功123')
							this.isRole = 2
						}

						this.count = users

						this.userList = result.data.list
					})
					if (this.countdown === 0) {
						uni.showToast({
							title: '游戏开始失败',
							icon: 'none'
						})
						uni.reLaunch({
							url: '/pages/index/index'
						})

					}
				}, 1000);


			},
			//进入房间倒计时
			handInit(roomId) {
				const that = this

				// 开始倒计时
				this.countdown = 120;
				this.timer = setInterval(() => {
					this.countdown--;
					console.log(this.countdown)

					GameRoomApi.getUserList({
						roomId: roomId
					}).then(result => {
						var users = result.data.count


						if (users >= 2) {

							console.log('成功99')
							//clearInterval(this.timer);
							this.isRole = 2
						}
						this.count = users

						this.userList = result.data.list
					})
					if (this.countdown === 0) {
						uni.showToast({
							title: '游戏开始失败',
							icon: 'none'
						})
						uni.reLaunch({
							url: '/pages/index/index'
						})

					}
				}, 1000);


			},

			// 加入
			handJoin(role) {
				//this.isRole = role
				GameRoomApi.join({
						room_id: this.roomId
					})
					.then(result => {
						this.isRole = 2

					})
			},
			handRoom() {
				//产生题目

				GameRoomApi.add_tiku({
						room_id: this.roomId
					})
					.then(result => {
						uni.redirectTo({
							url: '/pagesNew/multiple/room?roomId=' + this.roomId
						})

					})

			},
			/**
			 * 分享当前页面
			 */
			onShareAppMessage() {
				const app = this
				// 构建页面参数
				const params = app.$getShareUrlParams({
					roomId: app.roomId,
					isRole: 1
				});
				return {
					title: '一战到底',
					path: "/pagesNew/multiple/wait?" + params
				}
			},
		},

	}
</script>

<style lang="scss">
	.share-btn {
		background-color: #0197F8;
		color: #FFF;
		border-radius: 50rpx;

	}

	.hi {
		position: fixed;
		right: 0;
		bottom: 100rpx;
		z-index: 1;
		width: 500rpx;
		height: 372rpx;
	}

	.layout-position {
		position: relative;
		z-index: 99;
	}

	.layout-music {
		padding: 20rpx 36rpx;

		.text {
			font-size: 36rpx;
			line-height: 38rpx;
			color: #101010;
		}
	}

	.layout-multiple {
		margin: 36rpx 40rpx 0;
		padding: 20rpx 0;

		// border-radius: 10rpx;
		// box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.4);
		// background-color: rgba(255, 255, 255, 0.1);
		.item {
			margin-bottom: 20rpx;
			padding: 10rpx 0;

			.nickname {
				width: 100%;
				height: 32rpx;
				font-size: 32rpx;
				line-height: 32rpx;
				text-align: center;
				color: #101010;
			}

			.score {
				height: 60rpx;
				font-weight: 600;

				.nmb {
					font-size: 40rpx;
					color: #FC2A2A;
				}

				.sm {
					margin-left: 10rpx;
					font-size: 32rpx;
					color: #0197F8;
				}

				.add {
					color: #0197F8;
				}

				.sub {
					color: #FC2A2A;
				}
			}
		}
	}

	.layout-wait {
		margin: 50rpx auto 0;
		width: 580rpx;
	}

	.result-btn {
		margin: 0 auto;
		width: 580rpx;
		height: 80rpx;
		font-size: 36rpx;
		font-weight: 600;
		color: #fff;
		background: #0197F8;
		// border-radius: 40rpx;
		border: none;
	}

	.ready {
		font-size: 36rpx;
		font-weight: bold;
		color: #898989;
		text-align: center;
	}
</style>